<link rel="stylesheet" href="../assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/css/bootstrap-table.css">
<link rel="stylesheet" href="../assets/css/sweetalert.css">
<link rel="stylesheet" href="../assets/css/bootstrapValidator.min.css">
<link rel="stylesheet" href="../assets/css/bootstrap-datepicker3.min.css">
<script src="../assets/js/jquery-2.1.4.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/bootstrap-table.js"></script>
<script src="../assets/js/bootstrap-table-export.js"></script>
<script src="../assets/js/bootstrapValidator.min.js"></script>
<script src="../assets/js/bootstrap-datepicker.min.js"></script>
<script src="../assets/js/bootstrap-datepicker.zh-CN.js"></script>
<script src="http://rawgit.com/hhurz/tableExport.jquery.plugin/master/tableExport.js"></script>
<script src="../assets/js/bootstrap-table-zh-CN.js"></script>
<script src="../assets/js/sweetalert.min.js"></script>
<title>外出申请管理</title>
<style>
    .btn-default {
        height: 34px
    }

    .form-control {
        height: 30px
    }
</style>
<hr>
<div class="container" style="width:90%; height: auto">
    <h1>外出申请管理</h1>
    <form class="form-inline" id="searchForm" style="padding:2px 5px">
        <div class="form-group">
            <label>员工姓名:</label>
            <input class="form-control" type="text" id="searchEmployeeName" name="employeeName">
        </div>
        &#12288;
        <div class="form-group">
            <label>状态:</label>
            <select class="form-control" id="searchState" name="state" style="width: 196px">
                <option value="">所有</option>
                <option value="1">待审</option>
                <option value="2">部门通过</option>
                <option value="3">通过</option>
                <option value="4">拒绝</option>
            </select>
        </div>
        <br>
        <div class="form-group" style="padding: 4px 0 4px 0">
            <label for="datepicker">申请日期:</label>
            <div class="input-daterange input-group" id="datepicker" style="width:86%">
                <input class="form-control datepicker" readonly="readonly" type="text" placeholder="起始时间"
                       id="searchStartTime" name="timeStart" style="background-color: rgba(221, 221, 221, 0)">
                <span class="input-group-addon add-on">&nbsp;-&nbsp;</span>
                <input class="form-control datepicker" readonly="readonly" type="text" placeholder="结束时间"
                       id="searchEndTime" name="timeEnd" style="background-color: rgba(221, 221, 221, 0)">
            </div>
        </div>
        &#12288;
        <button type="button" class="btn btn-primary" onclick="searchAll()"
                style="height: 30px;vertical-align: middle"><i class="glyphicon glyphicon-search"></i> 搜索
        </button>
    </form>
    <hr>
    <div id="toolbar">
        <button id="add" class="btn btn-primary" data-toggle="modal" data-target="#addModal">
            <i class="glyphicon glyphicon-plus"></i> 添加
        </button>
        <button id="remove" class="btn btn-danger" onclick="removeRecord()">
            <i class="glyphicon glyphicon-remove"></i> 删除
        </button>
    </div>
    <table id="table" class="table-responsive"
           data-toolbar="#toolbar"
           data-search="false"
           data-show-refresh="true"
           data-show-toggle="true"
           data-show-export="true"
           data-minimum-count-columns="2"
           data-pagination="true"
           data-unique-id="id"
           data-page-number="1"
           data-page-size="10"
           data-page-list="[10, 20, 30, 40]"
           data-pagination-pre-text="上一页"
           data-pagination-next-text="下一页"
           data-show-footer="false"
           data-side-pagination="server"
           data-valign="middle"
           data-url="/fields/"
           data-query-params="queryParams"
           data-response-handler="responseHandler">
    </table>
</div>
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">添加外出申请记录</h4>
            </div>
            <div class="modal-body" style="text-align: center">
                <form class="form-horizontal" id="addFieldForm" role="form">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">员工工号:</label>
                        <div class="col-sm-6">
                            <input class="form-control" type="text" name="employeeCode">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="addDatepicker">请假日期:</label>
                        <div class="col-sm-6">
                            <div class="input-daterange input-group" id="addDatepicker" style="">
                                <input class="form-control datepicker" readonly="readonly" type="text"
                                       placeholder="起始时间" id="addStartTime" name="startTime"
                                       style="background-color: rgba(221, 221, 221, 0)" required="true">
                                <span class="input-group-addon add-on">&nbsp;-&nbsp;</span>
                                <input class="form-control datepicker" readonly="readonly" type="text"
                                       placeholder="结束时间" id="addEndTime" name="endTime"
                                       style="background-color: rgba(221, 221, 221, 0)" required="required">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">状态:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="addState" name="state">
                                <option value="1">待审</option>
                                <option value="2">部门通过</option>
                                <option value="3">通过</option>
                                <option value="4">拒绝</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">原因:</label>
                        <div class="col-sm-6">
                            <textarea class="form-control" name="reason" rows="3"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary" onclick="saveField()">保存</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h4 class="modal-title" id="">编辑外出申请记录</h4>
            </div>
            <div class="modal-body" style="text-align: center">
                <form class="form-horizontal" id="editForm" role="form">
                    <input type="hidden" name="_method" value="put" />
                    <div class="form-group" hidden="true">
                        <label class="col-sm-2 control-label">编号:</label>
                        <div class="col-sm-6">
                            <input class="form-control" type="text" id="editId" name="id">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">员工工号:</label>
                        <div class="col-sm-6">
                            <input class="form-control" type="text" id="editEmployeeCode" name="employeeCode">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">状态:</label>
                        <div class="col-sm-6">
                            <select class="form-control" id="editState" name="state">
                                <option value="1">待审</option>
                                <option value="2">部门通过</option>
                                <option value="3">通过</option>
                                <option value="4">拒绝</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label" for="editDatepicker">请假日期:</label>
                        <div class="col-sm-6">
                            <div class="input-daterange input-group" id="editDatepicker" style="">
                                <input class="form-control datepicker" readonly="readonly" type="text"
                                       placeholder="起始时间" id="editStartTime" name="startTime"
                                       style="background-color: rgba(221, 221, 221, 0)">
                                <span class="input-group-addon add-on">&nbsp;-&nbsp;</span>
                                <input class="form-control datepicker" readonly="readonly" type="text"
                                       placeholder="结束时间" id="editEndTime" name="endTime"
                                       style="background-color: rgba(221, 221, 221, 0)">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">原因:</label>
                        <div class="col-sm-6">
                                <textarea class="form-control" name="reason" rows="3" id="editReason"
                                          name="reason"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">回复:</label>
                        <div class="col-sm-6">
                            <input class="form-control" type="text" id="editReply" name="reply">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="submit" name="submit" class="btn btn-primary" onclick="updateField()">保存</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        /*$('form').bootstrapValidator({
         message: 'This value is not valid',
         feedbackIcons: {
         valid: 'glyphicon glyphicon-ok',
         invalid: 'glyphicon glyphicon-remove',
         validating: 'glyphicon glyphicon-refresh'
         },
         fields: {
         name: {
         message: '用户名验证失败',
         validators: {
         notEmpty: {
         message: '用户名不能为空'
         },
         stringLength: {
         min: 6,
         max: 18,
         message: '用户名长度必须在6到18位之间'
         },
         regexp: {
         regexp: /^[a-zA-Z0-9_]+$/,
         message: '用户名只能包含大写、小写、数字和下划线'
         }
         }
         },
         email: {
         validators: {
         notEmpty: {
         message: '邮箱不能为空'
         },
         emailAddress: {
         message: '邮箱地址格式有误'
         }
         }
         }
         },
         submitHandler: function (validator, form, submitButton) {
         }
         });*/
        $(".input-daterange").datepicker({
            language: "zh-CN",
            format: "yyyy-mm-dd",
            autoclose: true,
            clearBtn: true,
            todayHighlight: true
        }).on('hide',function(e) {
            $('#editForm').data('bootstrapValidator')
                    .updateStatus('startTime', 'NOT_VALIDATED',null)
                    .validateField('startTime');
            $('#editForm').data('bootstrapValidator')
                    .updateStatus('endTime', 'NOT_VALIDATED',null)
                    .validateField('endTime');
            $('#addFieldForm').data('bootstrapValidator')
                    .updateStatus('startTime', 'NOT_VALIDATED',null)
                    .validateField('startTime');
            $('#addFieldForm').data('bootstrapValidator')
                    .updateStatus('endTime', 'NOT_VALIDATED',null)
                    .validateField('endTime');
        });

        $("#table").bootstrapTable({
            height: 600,   //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            showColumns: true, //显示隐藏列
            striped: true,
            singleSelect: true,
            columns: [
                {
                    field: 'ck',
                    checkbox: true,
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '编号',
                    field: 'id',
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '员工姓名',
                    field: 'employeeName',
                    align: 'center',
                    valign: 'middle'
                },
                {
                    title: '开始日期',
                    field: 'startTime',
                    align: 'center',
                    valign: 'middle',
                    formatter: dateFormatter
                }, {
                    title: '结束日期',
                    field: 'endTime',
                    align: 'center',
                    valign: 'middle',
                    formatter: dateFormatter
                },  {
                    title: '原因',
                    field: 'reason',
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '状态',
                    field: 'state',
                    align: 'center',
                    valign: 'middle',
                    formatter: stateFormatter
                }, {
                    title: '回复',
                    field: 'reply',
                    align: 'center',
                    valign: 'middle'
                },
                {
                    title: '操作',
                    field: 'operate',
                    align: 'center',
                    valign: 'middle',
                    formatter: operateFormatter
                }
            ]
        });
        $('#table').bootstrapTable('hideColumn', 'id');

        formValidator();
        $("#addModal").on("hidden.bs.modal", function () {
            document.getElementById("addFieldForm").reset();
            $("#addFieldForm").data('bootstrapValidator').destroy();
            $('#addFieldForm').data('bootstrapValidator', null);
            formValidator();
        });
        $("#editModal").on("hidden.bs.modal", function () {
            document.getElementById("editForm").reset();
            $("#editForm").data('bootstrapValidator').destroy();
            $('#editForm').data('bootstrapValidator', null);
            formValidator();
        });
    });

    function queryParams(params) {
        return {
            pageSize: params.limit,
            pageNumber: $('#table').bootstrapTable('getOptions').pageNumber,
            sort: params.sortName,
            order: params.sortOrder,
            employeeName: $("#searchEmployeeName").val(),
            state: $("#searchState").val(),
            startTime: $("#searchStartTime").datepicker("getDate"),
            endTime: $("#searchEndTime").datepicker("getDate")
        };
    }
    function responseHandler(res) {
        return {
            "rows": res.fields.list,
            "total": res.fields.total
        }
    }
    function operateFormatter(value, row, index) {
        return [
            '<button id="edit" class="btn btn-success" onclick="edit(' + row.id + ')"><i class="glyphicon glyphicon-edit"></i> 修改</button>'
        ].join('');
    }
    function dateFormatter(value, row, index) {
        if (value != null)
            return new Date(value).Format("yyyy-MM-dd");
        else
            return "-";
    }
    function stateFormatter(value, row, index) {
        if (value == 10)
            return "待审";
        else if (value == 20)
            return "部门审过";
        else if (value == 30)
            return "通过";
        else
            return "拒绝"
    }
    function edit(id) {
        var row = $("#table").bootstrapTable("getRowByUniqueId", id);
        $('#editModal').modal('show');
        $("#editId").val(row.id);
        $("#editEmployeeCode").val(row.employeeCode);
        $("#editState").val(row.state);
        $("#editReason").val(row.reason);
        $("#editReply").val(row.reply);
        $("#editStartTime").datepicker("setDate", dateFormatter(row.startTime));
        $("#editEndTime").datepicker("setDate", dateFormatter(row.endTime));
    }

    function saveField() {
        //开启验证
        $('#addFieldForm').data('bootstrapValidator').validate();
        if (!$('#addFieldForm').data('bootstrapValidator').isValid()) {
            return;
        }
        $.ajax({
            url: "/fields/",
            type: 'POST',
            data: $("#addFieldForm").serialize(),
            async: false,
            success: function (result) {
                if (result.success) {
                    $("#addModal").modal('hide');
                    swal("Good job!", "添加成功", "success");
                    searchAll();
                } else {
                    sweetAlert("Oops...", result.message, "error");
                }
            },
            error: function (result) {
                sweetAlert("Oops...", "添加失败", "error");
            }
        });
    }

    function updateField() {
        //开启验证
        $('#editForm').data('bootstrapValidator').validate();
        if (!$('#editForm').data('bootstrapValidator').isValid()) {
            return;
        }
        $.ajax({
            url: "/fields/",
            type: 'post',
            data: $("#editForm").serialize(),
            async: false,
            success: function (result) {
                if (result.success) {
                    $("#editModal").modal('hide');
                    swal("Good job!", "修改成功", "success");
                    searchAll();
                } else {
                    sweetAlert("Oops...", result.message, "error");
                }
            },
            error: function (result) {
                sweetAlert("Oops...", "更新失败", "error");
            }
        });
    }

    function removeRecord() {
        var selections = $("#table").bootstrapTable("getSelections");
        if(selections == null || selections.length == 0){
            return;
        }
        swal({
                    title: "Are you sure?",
                    text: "是否要删除所选记录!",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "是",
                    cancelButtonText: "否",
                    closeOnConfirm: false
                },
                function () {
                    //var selections = $("#table").bootstrapTable("getSelections");
                    var id = selections[0].id;
//                    for (var i = 0; i < selections.length; i++) {
//                        strid += selections[i].id + ","
//                    }
                    $.ajax({
                        url: "/fields/"+id,
                        type: 'DELETE',
                        async: false,
                        success: function (result) {
                            if (result.success) {
                                swal("Deleted!", "删除成功.", "success");
                                searchAll();
                            } else {
                                sweetAlert("Oops...", result.message, "error");
                            }
                        },
                        error: function (result) {
                            sweetAlert("Oops...", "操作失败", "error");
                        }
                    });
                });
    }
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    function searchAll(){
        $("#table").bootstrapTable('refresh');
    }

    function formValidator() {
        $('#addFieldForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                employeeCode: {
                    message: '员工工号验证失败',
                    validators: {
                        notEmpty: {
                            message: '员工工号不能为空'
                        },
                        regexp: {
                            regexp: /^[0-9]*$/,
                            message: '工号只能包含数字'
                        }
                    }
                },
                startTime: {
                    validators: {
                        notEmpty: {
                            message: '开始日期不能为空'
                        }
                    }
                },
                endTime: {
                    validators: {
                        notEmpty: {
                            message: '结束日期不能为空'
                        }
                    }
                }
            },
            submitHandler: function (validator, form, submitButton) {
            }
        });
        $('#editForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                employeeCode: {
                    message: '员工工号验证失败',
                    validators: {
                        notEmpty: {
                            message: '员工工号不能为空'
                        },
                        regexp: {
                            regexp: /^[0-9]*$/,
                            message: '工号只能包含数字'
                        }
                    }
                },
                startTime: {
                    validators: {
                        notEmpty: {
                            message: '开始日期不能为空'
                        }
                    }
                },
                endTime: {
                    validators: {
                        notEmpty: {
                            message: '结束日期不能为空'
                        }
                    }
                }
            },
            submitHandler: function (validator, form, submitButton) {
            }
        });
    }
</script>